package com.videoplatform.controller;

import com.videoplatform.entity.Video;
import com.videoplatform.service.VideoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping("/api/upload")
public class FileUploadController {
    
    @Autowired
    private VideoService videoService;
    
    /**
     * 上传视频文件
     */
    @PostMapping("/video")
    @ResponseBody
    public ResponseEntity<Map<String, Object>> uploadVideo(
            @RequestParam("file") MultipartFile file,
            @RequestParam(value = "title", required = false) String title,
            @RequestParam(value = "description", required = false) String description) {
        
        Map<String, Object> response = new HashMap<>();
        
        try {
            Video video = videoService.uploadVideo(file, title, description);
            
            response.put("success", true);
            response.put("message", "视频上传成功");
            response.put("video", createVideoResponse(video));
            
            return ResponseEntity.ok(response);
            
        } catch (IllegalArgumentException e) {
            response.put("success", false);
            response.put("message", e.getMessage());
            return ResponseEntity.badRequest().body(response);
            
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "上传失败: " + e.getMessage());
            return ResponseEntity.internalServerError().body(response);
        }
    }
    
    /**
     * 获取上传进度（简单实现）
     */
    @GetMapping("/progress/{sessionId}")
    @ResponseBody
    public ResponseEntity<Map<String, Object>> getUploadProgress(@PathVariable String sessionId) {
        Map<String, Object> response = new HashMap<>();
        
        // 这里可以实现真实的进度跟踪
        // 目前返回模拟数据
        response.put("progress", 100);
        response.put("status", "completed");
        
        return ResponseEntity.ok(response);
    }
    
    /**
     * 创建视频响应对象
     */
    private Map<String, Object> createVideoResponse(Video video) {
        Map<String, Object> videoData = new HashMap<>();
        videoData.put("id", video.getId());
        videoData.put("title", video.getTitle());
        videoData.put("description", video.getDescription());
        videoData.put("fileName", video.getFileName());
        videoData.put("fileSize", video.getFileSize());
        videoData.put("uploadTime", video.getUploadTime().toString());
        videoData.put("status", video.getStatus().toString());
        videoData.put("viewCount", video.getViewCount());
        
        return videoData;
    }
}
